export default {
    name: 'CompanyForm',
    props: {
        value: Boolean, // 控制对话框显示
        title: String,  // 对话框标题
        formData: Object // 表单数据
    },
    data() {
        return {
            //表单数据
            formModel: this.getDefaultFormData(),
            // 表单验证规则
            formRules: {
                name: [
                    {required: true, message: '请输入公司名称', trigger: 'blur'},
                    {min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur'}
                ],
                establishmentDate: [
                    {required: true, message: '请选择成立日期', trigger: 'change'}
                ],
                registeredCapital: [
                    {required: true, message: '请输入注册资本', trigger: 'blur'},
                    {type: 'number', min: 0, message: '注册资本不能为负数', trigger: 'blur'}
                ],
                operating: [
                    {required: true, message: '请选择运营状态', trigger: 'change'}
                ]
            },
            // 提交状态
            submitting: false
        }
    },
    computed: {
        // 父组件v-model的dialogVisible，对话框的显示状态
        visible: {
            get() {
                return this.value
            },
            set(val) {
                //若更新visible，则通知父组件更新v-model的dialogVisible关闭对话框
                this.$emit('input', val)
            }
        }
    },
    watch: {
        /**
         * 监听父组件传来的formData，更新组件的formModel
         * 若直接v-model父组件的formData会导致违反单向数据流
         */
        formData: {
            immediate:true,
            handler(newVal) {
                if(newVal){
                    this.formModel={ ...this.getDefaultFormData(), ...newVal };
                }
            }
        }
    },
    methods: {
        //初始化空对象
        getDefaultFormData() {
            return {
                name: '',
                establishmentDate: '',
                registeredCapital: 0,
                operating: true
            };
        },
        //提交表单
        submitForm() {
            this.$refs.companyForm.validate(valid => {
                if (valid) {
                    this.submitting = true
                    // 提交数据到父组件
                    this.$emit('submit', this.formModel)
                }
            })
        },
        //重置表单
        resetForm() {
            this.$refs.companyForm.resetFields()
            this.$emit('reset')
        }
    }
}
